package com.mingyue.usercenter.service.impl;

import ch.qos.logback.core.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingyue.usercenter.common.Result;
import com.mingyue.usercenter.mapper.UserMapper;
import com.mingyue.usercenter.model.User;
import com.mingyue.usercenter.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

import static com.mingyue.usercenter.constant.userConstant.USER_LOGIN_STATE;

/**
 * @author 明月
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-12-01 22:57:24
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    public static final String MINGYUE = "mingyue";

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result userRegister(String userAccount, String userPassword, String checkPassword) {

        //1.字段不能为空
        if (StringUtil.isNullOrEmpty(userAccount) && StringUtil.isNullOrEmpty(userPassword) && StringUtil.isNullOrEmpty(checkPassword)) {
//            System.out.println("");
            return Result.error("字段不能为空");
        }

        //2.账户位数不能小于4
        if (userAccount.length() < 4) {
//            System.out.println("");
            return Result.error("账户位数不能小于4");
        }

        //3.密码不能小于8位
        if (userPassword.length() < 8) {
//            System.out.println("密码不能小于8位");
            return Result.error("密码不能小于8位");
        }

        //4.校验账户
//        不能以数字或特殊字符（这里指除了字母以外的任何字符）开头，可以使用以下正则表达式：
        String regex2 = "^[a-zA-Z][a-zA-Z0-9_-]*$";
        if(!userAccount.matches(regex2)){
//            System.out.println("");
            return Result.error("校验账户");
        }

        //5.校验密码
        if(!userPassword.equals(checkPassword)){
//            System.out.println("");
            return Result.error("校验密码");
        }

//        String regex2 = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";
//        if(!userPassword.matches(regex2)){
//            return -1;
//        }

        //判断数据库是否有重名账户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {

            return Result.error("该账户已被注册");
        }

        User user = new User();
        user.setUserAccount(userAccount);
        String jiaMiPassword = MINGYUE+userPassword;
        // 将字符串转换为字节数组
        byte[] passwordBytes = jiaMiPassword.getBytes();
        String jiaMi = DigestUtils.md5DigestAsHex(passwordBytes);
        user.setUserPassword(jiaMi);

        boolean res = this.save(user);
        if(!res){
            return Result.error("注册失败");
        }

        return Result.success();
    }

    @Override
    public Result userLogin(String userAccount, String userPassword, HttpServletRequest request) {


        //1.字段不能为空
        if (StringUtil.isNullOrEmpty(userAccount) && StringUtil.isNullOrEmpty(userPassword)) {
//            System.out.println("");
            return Result.error("字段不能为空");
        }

        //2.账户位数不能小于4
        if (userAccount.length() < 4) {
//            System.out.println("");
            return Result.error("账户位数不能小于4");
        }

        //3.密码不能小于8位
        if (userPassword.length() < 8) {
//            System.out.println("");
            return Result.error("密码不能小于8位");
        }

        //4.校验账户
//        不能以数字或特殊字符（这里指除了字母以外的任何字符）开头，可以使用以下正则表达式：
        String regex2 = "^[a-zA-Z][a-zA-Z0-9_-]*$";
        if(!userAccount.matches(regex2)){
//            System.out.println("");
            return Result.error("校验账户");
        }

        //加密
        String jiaMiPassword = MINGYUE+userPassword;
        // 将字符串转换为字节数组
        byte[] passwordBytes = jiaMiPassword.getBytes();
        String jiaMi = DigestUtils.md5DigestAsHex(passwordBytes);


        //判断数据库是否有重名账户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", jiaMi);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
//            log.info("");
            return Result.error("账号或密码错误");
        }

        //返回用户脱敏的信息
        User resUser = userTuoMin(user);

        /**
         * 把用户脱敏的信息存储到session,则session有值就是登录成功
         */
        request.getSession().setAttribute(USER_LOGIN_STATE,resUser);

        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);


        User user2 = (User)userObj;

        log.info("登录获取的session{}",user2);

        return Result.success(resUser);
    }

    @Override
    public List<User> searchUser(String username) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(!StringUtil.isNullOrEmpty(username) ){
            queryWrapper.like("username", username);
        }

        return userMapper.selectList(queryWrapper);
    }

    //用户脱敏信息
    @Override
    public User userTuoMin(User user){
        if(user == null){
            return null;
        }
        User user1 = new User();

        user1.setId(user.getId());
        user1.setUsername(user.getUsername());
        user1.setUserAccount(user.getUserAccount());
        user1.setAvatarUrl(user.getAvatarUrl());
        user1.setGender(user.getGender());
        user1.setPhone(user.getPhone());
        user1.setEmail(user.getEmail());
        user1.setUserStatus(user.getUserStatus());
        user1.setCreateTime(user.getCreateTime());
        user1.setUpdateTime(user.getUpdateTime());
        user1.setRole(user.getRole());
        return user1;

    }

    @Override
    public Integer userLogout(HttpServletRequest request) {
       request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }


}




